package com.efounder.util;

import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;

/**
 * 
 * @author fengshuquan
 * 
 */

public class AsyncImageLoader {
	private static Bitmap bitmap = null;		
	private static ExecutorService executorService = Executors
			.newFixedThreadPool(3);

	private static AsyncImageLoader asyncImageLoader;

	public static AsyncImageLoader getInstance() {
		if (asyncImageLoader == null) {
			asyncImageLoader = new AsyncImageLoader();
		}
		return asyncImageLoader;
	}

	public static Bitmap loadBitMap(String imageUrl) {
		Future<Bitmap> future = executorService.submit(new GetBitmap(imageUrl));
		try {
			bitmap = future.get();
		} catch (InterruptedException e) {
			e.printStackTrace();
		} catch (ExecutionException e) {
			e.printStackTrace();
		}
		return bitmap;
	}
}

class GetBitmap implements Callable<Bitmap> {

	private String url;

	public GetBitmap(String url) {
		this.url = url;
	}

	@Override
	public Bitmap call() throws Exception {
		URL imgUrl = new URL(url);
		HttpURLConnection conn = (HttpURLConnection) imgUrl.openConnection();
		InputStream is = conn.getInputStream();
		Bitmap bitmap = BitmapFactory.decodeStream(is);
		return bitmap;
	}
}
